const request = ({ method = "get", url, data }) => {

   return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest()
        if (method.toLowerCase() === 'get') {
            url = `${url}?${obj2str(data)}`
            xhr.open(method, url)
            xhr.send()
        } else if (method.toLowerCase() === 'post') {
            xhr.open(method, url)
            xhr.send(obj2str(data))
        }
        xhr.onload = function () {
            resolve(JSON.parse(xhr.responseText))
        }
        xhr.onerror = function(){
            reject("请求出错")
        }

    })

}




//{k1:v1,k2:v2}  ==> k1=v1&k2=v2
function obj2str(obj) {
    let str = ""
    for (let key in obj) {
        str += `${key}=${obj[key]}&`
    }
    console.log(str)
    return str.slice(0, str.length - 1)
}